/*
 * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package top.continew.admin.asset.service.impl;

import lombok.RequiredArgsConstructor;

import org.springframework.stereotype.Service;

import top.continew.starter.extension.crud.service.BaseServiceImpl;
import top.continew.admin.asset.mapper.ConsumableTracksMapper;
import top.continew.admin.asset.model.entity.ConsumableTracksDO;
import top.continew.admin.asset.model.query.ConsumableTracksQuery;
import top.continew.admin.asset.model.req.ConsumableTracksReq;
import top.continew.admin.asset.model.resp.ConsumableTracksDetailResp;
import top.continew.admin.asset.model.resp.ConsumableTracksResp;
import top.continew.admin.asset.service.ConsumableTracksService;

/**
 * 耗材履历业务实现
 *
 * @author CharlieYan
 * @since 2025/05/19 09:53
 */
@Service
@RequiredArgsConstructor
public class ConsumableTracksServiceImpl extends BaseServiceImpl<ConsumableTracksMapper, ConsumableTracksDO, ConsumableTracksResp, ConsumableTracksDetailResp, ConsumableTracksQuery, ConsumableTracksReq> implements ConsumableTracksService {

    private final ConsumableTracksMapper consumableTracksMapper;

    @Override
    public Integer consumableInbound(ConsumableTracksDO consumableTracksDO) {
        // 入库
        consumableTracksDO.setType(0);

        // 新库存 = 现库存 + 入库数
        Integer quantity = consumableTracksMapper.selectConsumableStockQuantityByConsumableId(consumableTracksDO
            .getConsumableId()) + consumableTracksDO.getChangeNum();
        consumableTracksDO.setQuantity(quantity);
        return consumableTracksMapper.insert(consumableTracksDO);
    }

    @Override
    public Integer consumableUsage(ConsumableTracksDO consumableTracksDO) {
        // 领用
        consumableTracksDO.setType(1);
        // 新库存 = 现库存 - 入库数
        Integer quantity = consumableTracksMapper.selectConsumableStockQuantityByConsumableId(consumableTracksDO
            .getConsumableId()) - consumableTracksDO.getChangeNum();
        if (quantity < 0) {
            return -1;
        } else {
            consumableTracksDO.setQuantity(quantity);
            return consumableTracksMapper.insert(consumableTracksDO);
        }
    }

}